<template>
  <div class="TaskDialog">
    <el-dialog
      v-dialogDrag
      :title="title"
      :visible.sync="dialogVisible"
      :width="width"
      :before-close="handelClose"
      :close-on-click-modal="false"
      append-to-body
    >
      <div class="dialogContent">
        <div class="dialogContent_left">
          <div class="dialogContent_left_form">
            <div class="dialogContent_left_form_row">
              <span class="dialogContent_left_form_row_span">项目名称:</span>
              <span>
                <el-input
                  v-model="form.programName"
                  style="width:75%"
                  placeholder="请输入内容"
                  :disabled="true"
                />
              </span>
            </div>
            <div class="dialogContent_left_form_row">
              <span class="dialogContent_left_form_row_span">任务发起人:</span>
              <span>
                <el-input
                  v-model="form.editUserName"
                  style="width:75%"
                  placeholder="请输入内容"
                  :disabled="true"
                />
              </span>
            </div>
            <div class="dialogContent_left_form_row">
              <span class="dialogContent_left_form_row_span"><span style="color:red;font-size:15px">*</span>任务名称:</span>
              <span>
                <el-input
                  v-model="form.taskName"
                  style="width:75%"
                  placeholder="请输入内容"
                  :disabled="isFlag===1?true:false"
                />
              </span>
            </div>
            <div class="dialogContent_left_form_row">
              <span class="dialogContent_left_form_row_span"><span style="color:red;font-size:15px">*</span>开始时间:</span>
              <span>
                <!--   popper-class="date-style"   @change="changePickerYear('startTime')"  -->
                <el-date-picker
                  v-model="form.startTime"
                  style="width:75%;"
                  placeholder="开始时间"
                  type="date"
                  value-format="yyyy-MM-dd"
                  :disabled="isFlag===1?true:false"
                />
              </span>
            </div>
            <div class="dialogContent_left_form_row">
              <span class="dialogContent_left_form_row_span"><span style="color:red;font-size:15px">*</span>结束时间:</span>
              <span>
                <!--   popper-class="date-style"  @change="changePickerYear('endTime')" -->
                <el-date-picker
                  v-model="form.endTime"
                  style="width:75%;"
                  placeholder="结束时间"
                  type="date"
                  value-format="yyyy-MM-dd"
                  :disabled="isFlag===1?true:false"
                />
              </span>
            </div>
            <div style="margin-bottom:0px" class="dialogContent_left_form_row">
              <div v-if="isFlag!==1" class="fileContent">
                <div style="margin-bottom:5px;display:flex">
                  <span style="flex:1">上传文件:</span>
                  <el-popover
                    v-if="isFlag===2"
                    placement="right"
                    width="400"
                    trigger="click"
                  >
                    <div v-if="annexIds.length!==0">
                      <div v-for="(item,index) in annexIds" :key="index" style="margin-bottom:3px;display:flex">
                        <span style="flex:9" class="file_content_title" @click="showFile(item)">{{ item.originName }}</span>
                        <span style="flex:1;text-align: center;line-height: 22px;cursor:pointer" @click="deleteFile(item,index)"><i class="el-icon-delete" /></span>
                      </div>
                    </div>
                    <div v-else style="text-align: center;">
                      <img style="width:200px" src="@/assets/images/homePage/noReport.png">
                      <div>暂无文件上传</div>
                    </div>
                    <span slot="reference" class="fileLook">查看已上传文件</span>
                  </el-popover>
                </div>
                <el-upload
                  ref="upLoad"
                  :auto-upload="false"
                  class="upload-demo"
                  :headers="headers"
                  :on-success="handleSuccess"
                  :on-change="handleChange"
                  :on-remove="handleRemove"
                  :file-list="fileList"
                  :action="upLoadUrl"
                  :data="form"
                  multiple
                  name="files"
                  drag
                >
                  <div style="margin: 20px 0px;">
                    <svg-icon icon-class="fileIcon" />
                  </div>
                  <div>
                    <div class="el-upload__text">点击或将文件拖拽到这里上传 </div>
                    <div class="el-upload_type">支持扩展名：.rar .zip .doc .docx .pdf .jpg... </div>
                  </div>
                </el-upload>
              </div>
              <div v-else class="fileContent" style="height:200px;overflow-y:auto;text;">
                <div style="margin-bottom:5px">已上传文件:</div>
                <div v-if="annexIds.length!==0">
                  <div v-for="(item,index) in annexIds" :key="index" style="margin-bottom:3px" @click="showFile(item)">
                    <span><svg-icon style="font-size:10px;vertical-align: middle;" icon-class="file" /></span>
                    <span class="file_content_title">{{ item.originName }}</span>
                  </div>
                </div>
                <div v-else style="text-align: center;">
                  <img style="width:200px" src="@/assets/images/homePage/noReport.png">
                  <div>暂无文件上传</div>
                </div>
              </div>
            </div>
          </div>
        </div>
        <div class="dialogContent_right">
          <div class="dialogContent_right_title">
            <span style="color:red;font-size:15px">*</span>项目参与人:
          </div>
          <div class="dialogContent_right_tree">
            <div class="dialogContent_left_tips">
              <div class="dialogContent_left_tips_title">
                <div class="dialogContent_left_tips_title_left">已勾中:{{ toData.length }}条</div>
                <div class="dialogContent_left_tips_title_right">
                  <span>人员列表</span>
                  <span v-if="!isShowDisabled && isFlag===0 " style="font-size:12px">
                    <el-checkbox v-model="checked" @change="chooseCheck" />
                    全选
                  </span>
                </div>
              </div>
              <div style="padding:8px 10px">
                <el-input v-model="filterText" style="width: 90%;" placeholder="关键词搜索">
                  <i slot="suffix" class="el-input__icon el-icon-search" />
                </el-input>
              </div>
              <div class="dialogContent_left_treeContainer">
                <el-tree
                  ref="tree"
                  :data="participantsList"
                  show-checkbox
                  node-key="uuid"
                  highlight-current
                  :filter-node-method="filterNode"
                  :props="defaultProps"
                  @check-change="handleNodeClick"
                />
              </div>
            </div>
          </div>
          <div class="dialogContent_right_memo">
            <div>备注:</div>
            <div style="margin-top:15px">
              <el-input
                v-model="form.remark"
                type="textarea"
                :rows="8"
                placeholder="请输入备注"
                :disabled="isFlag===1?true:false"
              />
            </div>
          </div>
        </div>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button size="small" @click="handelClose">取 消</el-button>
        <el-popconfirm
          v-if="isFlag!==1"
          :title="titleDesc"
          @onConfirm="makeSure"
          @onCancel="cancelPop"
        >
          <el-button slot="reference" type="primary" size="small">提 交</el-button>
        </el-popconfirm>
      </span>
    </el-dialog>

  </div>

</template>

<script>
import { getGlobal } from '@/utils/global';
import { doTask, deleteTaskAnnex } from '@/api/taskPage/index';
import { validTime } from '@/utils/commonMethods.js';

export default {
  data() {
    return {
      isShowDisabled: false,
      isFlag: 0,
      titleDesc: '你确定要创建该项目吗？',
      toData: [],
      dialogVisible: false,
      width: '850px',
      title: '',
      fileList: [],
      upLoadUrl: '',
      checked: false,
      defaultProps: {
        children: 'children',
        label: 'trueName'
      },
      headers: {
        token: localStorage.getItem('xcToken')
      },
      treeHeight: '',
      filterText: '',
      participantsList: [],
      guid: '',
      bpm: {
        action: '',
        defId: '',
        destination: '',
        extendConf: {
          nodeId: ''

        },
        formType: '',
        instanceId: '',
        opinion: '',
        taskId: '',
        defKey: ''
      },
      form: {
        type: 'Y0012',
        // 创建的时候没有，修改的时候有的
        taskGuid: '',
        // 参与人
        participants: [],
        // 备注
        remark: '',
        // 参与单位及参与人
        enterprises: [],
        programGuid: '',
        programName: '',
        // 用户id
        editUser: '',
        // 用户名称
        editUserName: '',
        taskName: '',
        startTime: '',
        endTime: ''
      },
      annexIds: []
    };
  },
  watch: {
    filterText: {
      handler: function(val) {
        if (this.participantsList) {
          this.$refs.tree.filter(val);
        }
      }, deep: true
    }
  },
  mounted() {
    this.treeHeight = window.innerHeight - 400;
  },
  created() {
    getGlobal().then((all) => {
      this.upLoadUrl = `${all.url}/taskLibrary/editTask`;
    });
  },
  methods: {
    handleRemove(file, fileList) {
      this.fileList = fileList;
    },
    deleteFile(item, index) {
      this.$confirm('此操作将永久删除该文件, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        deleteTaskAnnex({
          programGuid: this.form.programGuid,
          id: item.id,
          taskGuid: this.guid
        }).then(res => {
          if (res.success) {
            this.$message({
              message: '删除成功',
              type: 'success'
            });
            this.annexIds.splice(index, 1);
            const node = JSON.parse(localStorage.getItem('programlist'));
            this.$parent.$parent.$refs.leftContainer.getprogramList();
            setTimeout(() => {
              this.$parent.$parent.$refs.leftContainer.handleRole(node);
              this.$parent.$parent.$refs.leftContainer.$refs.tree.setCurrentKey(node.csjProgramGuid);
            }, 500);
          } else {
            this.$message({
              message: '删除失败',
              type: 'warning'
            });
          }
        });
      }).catch(() => {

      });
    },
    showFile(item) {
      getGlobal().then((all) => {
        window.open(`${all.url}/onlinePreview?fileId=${item.id}`, '_blank');
      });
    },
    handleNodeClick(data, check) {
      // 只取底层
      this.toData = this.$refs.tree.getCheckedNodes(true);
    },
    // 取消
    cancelPop() {
    },
    // 确定上传
    makeSure() {
      if (this.form.startTime !== '' && this.form.endTime !== '') {
        if (validTime(this.form.startTime, this.form.endTime)) {
          this.commonUploadMethod();
        } else {
          this.$message({
            message: '开始时间不能大于结束时间',
            type: 'warning'
          });
        }
      } else {
        this.commonUploadMethod();
      }
    },
    commonUploadMethod() {
      let isSubmit = true;
      if (this.form.taskName === '') {
        this.$message({
          message: '任务名称不能为空',
          type: 'warning'
        });
        isSubmit = false;
      } else if (this.form.startTime === '') {
        this.$message({
          message: '开始时间不能为空',
          type: 'warning'
        });
        isSubmit = false;
      } else if (this.form.endTime === '') {
        this.$message({
          message: '结束不能为空',
          type: 'warning'
        });
        isSubmit = false;
      } else if (this.$refs.tree.getCheckedNodes(true).length === 0) {
        this.$message({
          message: '项目参与人不能为空',
          type: 'warning'
        });
        isSubmit = false;
      } else if ([...new Set(this.$refs.tree.getCheckedNodes(true).map(item => item.trueName))].length < this.$refs.tree.getCheckedNodes(true).length) {
        this.$message({
          message: '您勾选的人存在重复,请重新选择',
          type: 'warning'
        });
        isSubmit = false;
      }
      if (isSubmit) {
        let anginSubmit = true;
        var d = new Date();
        var str = d.getFullYear() + '-' + (d.getMonth() + 1) + '-' + d.getDate();// 获取当前实际日期
        if (Date.parse(str) > Date.parse(this.form.endTime)) { // 时间戳对比
          this.$message({
            message: '您选择的结束日期小于当前日期，请重新选择',
            type: 'warning'
          });
          anginSubmit = false;
        }
        if (anginSubmit) {
          this.form.enterprises = [];
          this.form.participants = [];
          this.$refs.tree.getCheckedNodes(true).map(a => {
            this.form.participants.push(a.userId);
            this.participantsList.map(b => {
              if (b.cEnterpriseCode === a.cEnterpriseCode) {
                if (this.form.enterprises.length === 0) {
                  this.form.enterprises.push({
                    enterpriseGuid: b.cEnterpriseCode,
                    participants: [a.userId]
                  });
                  return;
                }
                let count = 0;
                let flag = true;
                this.form.enterprises.map((item, index) => {
                  if (item.enterpriseGuid === b.cEnterpriseCode && item.enterpriseGuid) {
                    count = index;
                    flag = false;
                  }
                });
                if (flag) {
                  this.form.enterprises.push({
                    enterpriseGuid: b.cEnterpriseCode,
                    participants: [a.userId]
                  });
                } else {
                  this.form.enterprises[count].participants.push(a.userId);
                }
              }
            });
          });
          const param = new FormData();
          // 将得到的文件流添加到FormData对象
          if (this.fileList.length !== 0) {
            this.fileList.forEach(function(file) {
              param.append('files', file.raw);
            });
          }
          Object.keys(this.form).forEach((key) => {
            // 序列化
            if (key === 'participants' || key === 'enterprises') {
              param.append(key, JSON.stringify(this.form[key]));
            } else {
              param.append(key, this.form[key]);
            }
          });
          doTask(param).then(res => {
            if (res.success) {
              this.$message({
                message: res.message,
                type: 'success'
              });
              this.handelClose();
              const node = JSON.parse(localStorage.getItem('programlist'));
              this.$parent.$parent.$refs.leftContainer.getprogramList();
              setTimeout(() => {
                this.$parent.$parent.$refs.leftContainer.handleRole(node);
                this.$parent.$parent.$refs.leftContainer.$refs.tree.setCurrentKey(node.csjProgramGuid);
              }, 500);
            } else {
              this.$message({
                message: res.message,
                type: 'warning'
              });
            }
          });
        }
      }
    },
    chooseCheck() { // el-tree全选事件
      if (this.checked) { // 全选
        this.$refs.tree.setCheckedNodes(this.participantsList);
      } else { // 取消选中
        this.$refs.tree.setCheckedKeys([]);
      }
    },
    filterNode(val, data) {
      if (!val) return true;
      return data.trueName.indexOf(val) !== -1;
    },
    changePickerYear(type) {
      if (this.form[type]) {
        this.form[type] = localStorage.getItem('chooseYear') + '-' + this.form[type].split('-')[1] + '-' + this.form[type].split('-')[2];
      }
    },
    // 多文件上传（不支持相同文件名字的上传）
    handleChange(file, fileList) {
      // 这表示是添加行为
      // console.log(`准备修改文件${file.raw.name}, 此时文件列表长度为${fileList.length}`)
      if (file.status === 'ready') {
        // console.log(`添加了文件${file.raw.name}`)
        const myFile = file.raw;
        const fileIndex = this.getFileIndex(file, fileList);
        if (fileIndex > 1) {
          // fileList[fileIndex] = file;
          fileList.pop();
          this.$message({
            message: `${myFile.name}文件重复,无法上传`,
            type: 'warning'
          });
        }
      }
      this.fileList = fileList;
    },
    getFileIndex(file, fileList) {
      let count = 0;
      fileList.map(o => {
        if (o.name === file.name) {
          count++;
        }
      });
      return count;
    },
    handleSuccess(response) {
      if (response.success) {
        this.$message({
          message: response.message,
          type: 'success'
        });
        this.handelClose();
        const node = JSON.parse(localStorage.getItem('programlist'));
        this.$parent.$parent.$refs.leftContainer.getprogramList();
        setTimeout(() => {
          this.$parent.$parent.$refs.leftContainer.handleRole(node);
          this.$parent.$parent.$refs.leftContainer.$refs.tree.setCurrentKey(node.csjProgramGuid);
        }, 500);
      } else {
        this.$message({
          message: response.message,
          type: 'warning'
        });
      }
    },
    handelClose() {
      if (this.isFlag !== 1) {
        this.$refs.upLoad.clearFiles();
        this.$refs.tree.setCheckedKeys([]);
      }
      this.participantsList = [];
      this.toData = [];
      this.filterText = '';
      this.checked = false;
      this.fileList = [];
      this.form = {
        type: 'Y0012',
        // 创建的时候没有，修改的时候有的
        taskGuid: '',
        // 参与人
        participants: [],
        // 备注
        remark: '',
        // 参与单位及参与人
        enterprises: [],
        programGuid: '',
        programName: '',
        // 用户id
        editUser: '',
        // 用户名称
        editUserName: '',
        taskName: '',
        startTime: '',
        endTime: ''
      };
      this.dialogVisible = false;
    }
  }
};
</script>

<style lang='scss' scoped >
  .fileLook{
    flex:1;
    text-align:right;
    color:rgb(64, 158, 255);
    text-decoration:underline;
    cursor:pointer
  }

 .TaskDialog /deep/ .el-dialog {
  margin-top: calc(7vh) !important
}
 .TaskDialog /deep/ .el-dialog__body {
  padding: 8px 20px !important;
  color: #606266;
  font-size: 15px;
}
 .dialogContent{
  display: flex
}
.dialogContent_left{
  flex-basis:430px;
  flex-shrink:0;
  padding:5px
}
.dialogContent_right{
  width: 380px;
  padding: 5px 20px;
}
.dialogContent_left_form_row{
  margin-bottom: 25px
}
.dialogContent_left_form_row_span{
  margin-right: 10px;
  display: inline-block;
  width: 80px;
}
.fileContent{
      margin-top: 15px;
}
.el-upload__text{
  height: 24px;
  opacity: 1;
  font-size: 16px;
  font-family: PingFangSC, PingFangSC-Medium;
  font-weight: 500;
  text-align: center;
  color: rgba(0,0,0,0.85);
  line-height: 24px;
}
.dialogContent_left /deep/ .el-upload-list {
  margin: 0;
  padding: 0;
  list-style: none;
  height: 65px !important;
  overflow-y: auto !important;
}
.dialogContent_left /deep/ .el-upload{
  width: 100% !important;
}
.dialogContent_left /deep/  .el-upload-dragger{
  width: 100% !important;
  height: 155px;
}
.dialogContent_left /deep/ .svg-icon {
    width: 3.5em;
    height: 2em;
    vertical-align: -0.15em;
    fill: currentColor;
    overflow: hidden;
    font-size: 1.2rem;
}
.el-upload_type{
  height: 22px;
  opacity: 1;
  font-size: 14px;
  font-family: PingFangSC, PingFangSC-Medium;
  font-weight: 500;
  text-align: center;
  color: rgba(0,0,0,0.45);
  line-height: 22px;
  margin-top: 5px
}
.dialogContent_right_title{
  font-size: 15px;
  text-align: left;
  line-height: 20px;
}
.dialogContent_right_tree{
  margin-top: 10px
}
.dialogContent_left_tips{
  border: 1px solid rgba(0,0,0,0.15);
  border-radius: 3px;
  width: 100%;
}
.dialogContent_left_tips_title{
  display: flex;
  border-bottom: 1px solid rgba(0,0,0,0.15);
  height: 45px;
  line-height: 45px;
  padding: 0px 10px
}
.dialogContent_left_tips_title_right{
  flex:1;
  text-align:right;
  opacity: 1;
  font-size: 14px;
  font-family: PingFangSC, PingFangSC-Medium;
  font-weight: 500;
  color: rgba(0,0,0,0.65);
}
.dialogContent_left_tips_title_left{
  flex:1;
  opacity: 1;
  font-size: 14px;
  font-family: PingFangSC, PingFangSC-Medium;
  font-weight: 500;
  color: rgba(0,0,0,0.65);
}
.dialogContent_left_treeContainer{
  height: 148px;
  overflow-y: auto;
  padding:5px
}
.dialogContent_right_memo{
  margin-top: 20px;
}
.file_content_title{
  font-family: PingFangSC, PingFangSC-Regular;
  font-weight: 400;
  text-decoration: underline;
  text-align: left;
  color: #1890ff;
  line-height: 22px;
  text-decoration: underline;
  cursor: pointer;
}

</style>
